# -*- coding: utf-8 -*-

# Copyright 2011 Fanficdownloader team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys, os
from os.path import normpath, expanduser, isfile, join
from StringIO import StringIO
from optparse import OptionParser      
import getpass
import string
import ConfigParser
from subprocess import call

import logging
if sys.version_info >= (2, 7):
    # suppresses default logger.  Logging is setup in fanficdownload/__init__.py so it works in calibre, too.
    rootlogger = logging.getLogger()
    loghandler=logging.NullHandler()
    loghandler.setFormatter(logging.Formatter("(=====)(levelname)s:%(message)s"))
    rootlogger.addHandler(loghandler)

import astroph.adapters as adapters
import astroph.exceptions as exceptions
from astroph.configurable import Configuration
import astroph.base_writer as writers

if sys.version_info < (2, 5):
    print "This program requires Python 2.5 or newer."
    sys.exit(1)

def writePaper(config,adapter,metaonly=False,outstream=None):
    writer = writers.BasePaperWriter(config,adapter)
    writer.writePaper(outstream=outstream,metaonly=metaonly)
    output_filename=writer.getOutputFileName()
    del writer
    return output_filename

def main():
   # read in args, anything starting with -- will be treated as --<varible>=<value>
   usage = "usage: %prog [options] paperurl"
   parser = OptionParser(usage)
   parser.add_option("-f", "--format", dest="format", default="pdf",
                     help="write paper as FORMAT, epub(default), text or html", metavar="FORMAT")
   parser.add_option("-c", "--config",
                     action="append", dest="configfile", default=None,
                     help="read config from specified file(s) in addition to ~/.fanficdownloader/defaults.ini, ~/.fanficdownloader/personal.ini, ./defaults.ini, ./personal.ini", metavar="CONFIG")
   parser.add_option("-b", "--begin", dest="begin", default=None,
                     help="Begin with Chapter START", metavar="START")
   parser.add_option("-e", "--end", dest="end", default=None,
                     help="End with Chapter END", metavar="END")
   parser.add_option("-o", "--option",
                     action="append", dest="options",
                     help="set an option NAME=VALUE", metavar="NAME=VALUE")
   parser.add_option("-m", "--meta-only",
                     action="store_true", dest="metaonly",
                     help="Retrieve metadata and stop.  Or, if --update-epub, update metadata title page only.",)
   parser.add_option("-u", "--update-epub",
                     action="store_true", dest="update",
                     help="Update an existing epub with new chapters, give epub filename instead of paperurl.",)
   parser.add_option("--update-cover",
                     action="store_true", dest="updatecover",
                     help="Update cover in an existing epub, otherwise existing cover (if any) is used on update.  Only valid with --update-epub.",)
   parser.add_option("--force",
                     action="store_true", dest="force",
                     help="Force overwrite of an existing epub, download and overwrite all chapters.",)
   parser.add_option("-l", "--list",
                     action="store_true", dest="list",
                     help="Get list of valid paper URLs from page given.",)
   parser.add_option("-d", "--debug",
                     action="store_true", dest="debug",
                     help="Show debug output while downloading.",)
   
   (options, args) = parser.parse_args()
   
   url = args[0]

   if not options.debug:
       logger = logging.getLogger("astroph")
       logger.setLevel(logging.INFO)
   
   if len(args) != 1:
       parser.error("incorrect number of arguments")
           
   configuration = Configuration()

   conflist = []
   homepath = join(expanduser("~"),".astroph")
   
   if isfile(join(homepath,"defaults.ini")):
       conflist.append(join(homepath,"defaults.ini"))
   if isfile("defaults.ini"):
       conflist.append("defaults.ini")
       
   if isfile(join(homepath,"personal.ini")):
       conflist.append(join(homepath,"personal.ini"))
   if isfile("personal.ini"):
       conflist.append("personal.ini")
       
   if options.configfile:
       conflist.extend(options.configfile)
      
   logging.debug('reading %s config file(s), if present'%conflist)
   configuration.read(conflist)

   try:
       configuration.add_section("overrides")
   except ConfigParser.DuplicateSectionError:
       pass

   if options.force:
       configuration.set("overrides","always_overwrite","true")

   if options.update:
       configuration.set("overrides","output_filename",args[0])
       
   if options.update and not options.updatecover:
       configuration.set("overrides","never_make_cover","true")

   # images only for epub, even if the user mistakenly turned it
   # on else where.
   if options.format not in ("epub","html"):
       configuration.set("overrides","include_images","false")
       
   if options.options:
       for opt in options.options:
           (var,val) = opt.split('=')
           configuration.set("overrides",var,val)

   if options.list:
       retlist = get_urls_from_page(args[0], configuration)
       print "\n".join(retlist)
               
       return

   try:
       adapter = adapters.getAdapter(configuration,url)

       if options.metaonly:
           print adapter.getPaperMetadataOnly()
           
       output_filename=writePaper(configuration,adapter,options.format,options.metaonly)
       
           
       del adapter
   
   except exceptions.InvalidPaperURL, isu:
       print isu
   except exceptions.PaperDoesNotExist, dne:
       print dne
   except exceptions.UnknownSite, us:
       print us

if __name__ == "__main__":
    #import time
    #start = time.time()
    main()
    #print("Total time seconds:%f"%(time.time()-start))
